<template>
  <div class="app-container">
    <!-- 查询区域 -->
    <el-card class="search-card">
      <el-form :model="queryParams">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="计划名称">
              <el-input v-model="queryParams.planName" placeholder="请输入计划名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="计划日期">
              <el-date-picker v-model="queryParams.planDateRange" type="daterange" range-separator="至"
                start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="状态">
              <el-select v-model="queryParams.releaseStatus" placeholder="请选择状态" clearable>
                <el-option label="未发布" value="0" />
                <el-option label="已发布" value="1" />
                <el-option label="已执行" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" style="text-align: left;">
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 数据表格区域 -->
    <el-card class="mt-1">
      <el-button type="primary" @click="handleAdd">
        <el-icon>
          <Plus />
        </el-icon>
        新增计划
      </el-button>
      <el-table :data="schedulePlanList" border v-loading="loading" class="mt-2"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="planName" label="计划名称"  align="center" />
        <el-table-column prop="pumpGroup" label="泵组" align="center" />
        <el-table-column prop="planDate" label="计划日期" align="center" />
        <el-table-column prop="planStartTime" label="开始时间" align="center" />
        <el-table-column prop="planEndTime" label="结束时间" align="center" />
        <el-table-column prop="creator" label="制定人" align="center" />
        <el-table-column prop="releaseStatus" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.releaseStatus)">
              {{ getStatusLabel(row.releaseStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="releaseTime" label="发布时间" width="180" align="center" />
        <el-table-column label="操作" width="220" align="center">
          <template #default="{ row }">
            <el-button size="small" @click="handleView(row)">查看</el-button>
            <el-button size="small" type="primary" @click="handleEdit(row)" :disabled="row.releaseStatus !== '0'">
              编辑
            </el-button>
            <el-button size="small" type="success" @click="handleExecute(row)" v-if="row.releaseStatus === '1'">
              执行
            </el-button>
            <el-button size="small" type="warning" @click="handlePublish(row)" v-if="row.releaseStatus === '0'">
              发布
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)" :disabled="row.releaseStatus !== '0'">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination class="mt-2" background layout="total, sizes, prev, pager, next, jumper" :total="total"
        v-model:page-size="queryParams.pageSize" v-model:current-page="queryParams.pageNum"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="800px" :close-on-click-modal="false">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="计划名称" prop="planName">
          <el-input v-model="form.planName" placeholder="请输入计划名称" />
        </el-form-item>

        <el-form-item label="泵组选择" prop="pumpGroupIds">
          <el-select v-model="form.pumpGroupIds" multiple placeholder="请选择泵组" style="width: 100%">
            <el-option v-for="item in pumpGroupOptions" :key="item.pumpGroupId" :label="item.pumpGroupName"
              :value="item.pumpGroupId" />
          </el-select>
        </el-form-item>

        <el-form-item label="计划日期" prop="planDate">
          <el-date-picker v-model="form.planDate" type="date" placeholder="选择计划日期" value-format="YYYY-MM-DD"
            style="width: 100%" />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始时间" prop="planStartTime">
              <el-time-picker v-model="form.planStartTime" placeholder="选择开始时间" value-format="HH:mm:ss"
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="planEndTime">
              <el-time-picker v-model="form.planEndTime" placeholder="选择结束时间" value-format="HH:mm:ss"
                style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="运行参数" prop="runParam">
          <el-input v-model="form.runParam" type="textarea" :rows="3" placeholder="请输入运行参数" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialog.visible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </template>
    </el-dialog>

    <!-- 执行对话框 -->
    <el-dialog v-model="executeDialog.visible" title="执行调度计划" width="500px">
      <el-form :model="executeForm" label-width="100px">
        <el-form-item label="计划名称">
          <el-input v-model="executeDialog.planName" disabled />
        </el-form-item>
        <el-form-item label="实际开始时间" prop="actualStartTime">
          <el-date-picker v-model="executeForm.actualStartTime" type="datetime" placeholder="选择实际开始时间"
            value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
        </el-form-item>
        <el-form-item label="实际结束时间" prop="actualEndTime">
          <el-date-picker v-model="executeForm.actualEndTime" type="datetime" placeholder="选择实际结束时间"
            value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="executeDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="confirmExecute">确认执行</el-button>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialog.visible" :title="`调度计划详情 - ${detailDialog.data.planName}`" width="800px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="计划ID" :span="1">{{ detailDialog.data.schedulePlanId || '-' }}</el-descriptions-item>
        <el-descriptions-item label="计划名称" :span="1">{{ detailDialog.data.planName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="泵组" :span="2">
          <div v-if="detailDialog.data.pumpGroupIds && detailDialog.data.pumpGroupIds.length > 0">
            <el-tag v-for="pumpGroupId in detailDialog.data.pumpGroupIds" :key="pumpGroupId" class="mr-1 mb-1">
              {{ getPumpGroupName(pumpGroupId) }}
            </el-tag>
          </div>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="计划日期">{{ detailDialog.data.planDate || '-' }}</el-descriptions-item>
        <el-descriptions-item label="计划时间">
          {{ detailDialog.data.planStartTime || '-' }} 至 {{ detailDialog.data.planEndTime || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="运行参数" :span="2">
          <pre class="pre-formatted">{{ detailDialog.data.runParam || '无' }}</pre>
        </el-descriptions-item>
        <el-descriptions-item label="制定人">{{ detailDialog.data.creator || '-' }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusTagType(detailDialog.data.releaseStatus)">
            {{ getStatusLabel(detailDialog.data.releaseStatus) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="发布时间">{{ detailDialog.data.releaseTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="实际开始时间">{{ detailDialog.data.actualStartTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="实际结束时间">{{ detailDialog.data.actualEndTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ detailDialog.data.remark || '无' }}</el-descriptions-item>
      </el-descriptions>

      <template #footer>
        <el-button @click="detailDialog.visible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {
  getPumpGroupList,
  listSchedulePlan,
  getSchedulePlanDetail,
  addSchedulePlan,
  updateSchedulePlan,
  deleteSchedulePlan,
  publishSchedulePlan,
  executeSchedulePlan
} from '@/api/dispatch/affair/dispatch_plan'

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  planName: '',
  planDateRange: [],
  releaseStatus: undefined
})

// 表单数据
const form = reactive({
  schedulePlanId: undefined,
  planName: '',
  pumpGroupIds: [],
  planDate: '',
  planStartTime: '',
  planEndTime: '',
  runParam: ''
})

// 执行表单数据
const executeForm = reactive({
  schedulePlanId: undefined,
  actualStartTime: '',
  actualEndTime: ''
})

// 对话框控制
const dialog = reactive({
  visible: false,
  title: ''
})

const executeDialog = reactive({
  visible: false,
  planName: ''
})

const detailDialog = reactive({
  visible: false,
  data: {}
})

// 下拉选项数据
const pumpGroupOptions = ref([])

// 表格数据
const schedulePlanList = ref([])
const total = ref(0)
const loading = ref(false)
const selectedRows = ref([])
const formRef = ref()

// 表单验证规则
const rules = reactive({
  planName: [
    { required: true, message: '请输入计划名称', trigger: 'blur' }
  ],
  pumpGroupIds: [
    { required: true, message: '请选择泵组', trigger: 'change' }
  ],
  planDate: [
    { required: true, message: '请选择计划日期', trigger: 'change' }
  ],
  planStartTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  planEndTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ]
})

// 获取状态标签类型
const getStatusTagType = (status) => {
  const map = {
    '0': 'info',    // 未发布
    '1': 'warning', // 已发布
    '2': 'success'  // 已执行
  }
  return map[status] || 'info'
}

// 获取状态标签文本
const getStatusLabel = (status) => {
  const map = {
    '0': '未发布',
    '1': '已发布',
    '2': '已执行'
  }
  return map[status] || '未知'
}

// 获取泵组名称
const getPumpGroupName = (pumpGroupId) => {
  const pumpGroup = pumpGroupOptions.value.find(item => item.pumpGroupId === pumpGroupId)
  return pumpGroup ? pumpGroup.pumpGroupName : pumpGroupId
}

// 获取泵组下拉列表
const fetchPumpGroupList = async () => {
  try {
    const res = await getPumpGroupList()
    pumpGroupOptions.value = res.data || []
  } catch (error) {
    console.error('获取泵组列表失败:', error)
    ElMessage.error('获取泵组列表失败')
  }
}

// 获取调度计划列表
const fetchSchedulePlanList = async () => {
  try {
    loading.value = true

    // 处理日期范围参数
    const params = {
      ...queryParams,
      startTime: queryParams.planDateRange?.[0] || '',
      endTime: queryParams.planDateRange?.[1] || ''
    }

    const res = await listSchedulePlan(params)
    schedulePlanList.value = res.rows || []
    total.value = res.total || 0
  } catch (error) {
    console.error('获取调度计划列表失败:', error)
    ElMessage.error('获取调度计划列表失败')
  } finally {
    loading.value = false
  }
}

// 获取调度计划详情
const fetchSchedulePlanDetail = async (id) => {
  try {
    const res = await getSchedulePlanDetail(id)
    return res
  } catch (error) {
    console.error('获取调度计划详情失败:', error)
    throw error
  }
}

// 查询按钮
const handleQuery = () => {
  queryParams.pageNum = 1
  fetchSchedulePlanList()
}

// 重置查询
const resetQuery = () => {
  queryParams.pageNum = 1
  queryParams.planName = ''
  queryParams.planDateRange = []
  queryParams.releaseStatus = undefined
  fetchSchedulePlanList()
}

// 分页大小变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  fetchSchedulePlanList()
}

// 当前页码变化
const handleCurrentChange = (page) => {
  queryParams.pageNum = page
  fetchSchedulePlanList()
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 新增按钮
const handleAdd = () => {
  dialog.visible = true
  dialog.title = '新增调度计划'

  // 重置表单
  if (formRef.value) {
    formRef.value.resetFields()
  }

  Object.assign(form, {
    schedulePlanId: undefined,
    planName: '',
    pumpGroupIds: [],
    planDate: '',
    planStartTime: '',
    planEndTime: '',
    runParam: ''
  })
}

// 编辑按钮
const handleEdit = async (row) => {
  try {
    const res = await fetchSchedulePlanDetail(row.schedulePlanId)
    
    // 根据接口返回的数据结构处理
    const detailData = res.data || {}
    Object.assign(form, {
      schedulePlanId: detailData.schedulePlanId,
      planName: detailData.planName,
      pumpGroupIds: detailData.pumpGroupIds || [],
      planDate: detailData.planDate,
      planStartTime: detailData.planStartTime,
      planEndTime: detailData.planEndTime,
      runParam: detailData.runParam || ''
    })

    dialog.visible = true
    dialog.title = '编辑调度计划'
  } catch (error) {
    console.error('获取调度计划详情失败:', error)
    ElMessage.error('获取调度计划详情失败')
  }
}

// 查看详情
const handleView = async (row) => {
  try {
    const res = await fetchSchedulePlanDetail(row.schedulePlanId)
    
    // 根据接口返回的数据结构处理
    detailDialog.data = res.data || {}
    detailDialog.visible = true
  } catch (error) {
    console.error('获取调度计划详情失败:', error)
    ElMessage.error('获取调度计划详情失败')
  }
}

// 发布按钮
const handlePublish = (row) => {
  ElMessageBox.confirm(`确认发布调度计划 "${row.planName}" 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    return publishSchedulePlan(row.schedulePlanId)
  }).then(() => {
    ElMessage.success('发布成功')
    fetchSchedulePlanList()
  }).catch(() => { })
}

// 执行按钮
const handleExecute = (row) => {
  executeDialog.planName = row.planName
  executeForm.schedulePlanId = row.schedulePlanId
  executeForm.actualStartTime = ''
  executeForm.actualEndTime = ''
  executeDialog.visible = true
}

// 确认执行
const confirmExecute = async () => {
  if (!executeForm.actualStartTime) {
    ElMessage.error('请选择实际开始时间')
    return
  }

  if (!executeForm.actualEndTime) {
    ElMessage.error('请选择实际结束时间')
    return
  }

  try {
    await executeSchedulePlan(executeForm)
    ElMessage.success('执行成功')
    executeDialog.visible = false
    fetchSchedulePlanList()
  } catch (error) {
    console.error('执行调度计划失败:', error)
    ElMessage.error('执行调度计划失败')
  }
}

// 删除按钮
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除调度计划 "${row.planName}" 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    return deleteSchedulePlan(row.schedulePlanId)
  }).then(() => {
    ElMessage.success('删除成功')
    fetchSchedulePlanList()
  }).catch(() => { })
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()

    const isAdd = form.schedulePlanId === undefined
    const api = isAdd ? addSchedulePlan : updateSchedulePlan

    await api(form)
    ElMessage.success('操作成功')
    dialog.visible = false
    fetchSchedulePlanList()
  } catch (error) {
    console.error('保存调度计划失败:', error)
  }
}

// 初始化加载数据
onMounted(() => {
  fetchPumpGroupList()
  fetchSchedulePlanList()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.search-card,
.mt-1 {
  margin-bottom: 20px;
}

.mt-2 {
  margin-top: 20px;
}

.pre-formatted {
  white-space: pre-wrap;
  word-wrap: break-word;
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
  border: 1px solid #e0e0e0;
  font-family: 'Courier New', monospace;
  font-size: 14px;
  line-height: 1.5;
}

.mr-1 {
  margin-right: 8px;
}

.mb-1 {
  margin-bottom: 8px;
}

:deep(.el-descriptions) {
  margin-top: 20px;
}

:deep(.el-descriptions__label) {
  font-weight: 600;
  color: #606266;
}

:deep(.el-descriptions__content) {
  color: #303133;
}
</style>